package com.myapp.listener;

import java.io.File;
import java.io.FileNotFoundException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

/**
 * 
 * @author liuzy
 * @since 2016年8月30日
 */
public class MyServletContextListener implements ServletContextListener {
	private Logger logger = Logger.getLogger(MyServletContextListener.class);

	public static final String configDirName = System.getProperty("configDirName", "appCfg");

	private static String configDirPath = System.getProperty("configDirPath");

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.info("MyServletContextListener contextInitialized()");
		if (configDirPath == null) {
			String classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
			logger.info("classpath: " + classPath);
			if (classPath.contains("target")) {
				configDirPath = classPath.substring(0, classPath.indexOf("target")) + configDirName + "/";
			} else if (classPath.contains("webapps")) {
				configDirPath = classPath.substring(0, classPath.indexOf("webapps")) + configDirName + "/";
			} else {
				throw new RuntimeException("set configDirPath failed !");
			}
			logger.info("configDirPath: " + configDirPath);
			System.setProperty(configDirName, configDirPath);
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		logger.info("MyServletContextListener contextDestroyed()");
	}

	public static String getConfigDirPath() {
		return MyServletContextListener.configDirPath;
	}

	public static File getConfigFile(String fileName) throws FileNotFoundException {
		File file = new File(MyServletContextListener.configDirName + fileName);
		if (file.isFile()) {
			return file;
		} else {
			throw new FileNotFoundException(MyServletContextListener.configDirName + fileName + "not found !");
		}
	}

}
